package com.streambolics.servlet;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.streambolics.mail.BeanMimeParser;

@SuppressWarnings("serial")
public abstract class EmailParser extends HttpServlet
{
    private MimeMessage _Message;

    @Override
    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        try
        {
            setupEnvironment (req, resp);
            try
            {
                performOperations ();
            }
            catch (Exception e)
            {
                // TODO : Create a response e-mail indicating that the operation
                // could not be carried out.
            }
            finally
            {
                teardownEnvironment ();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace ();
        }
    }

    public MimeMessage getMessage ()
    {
        return _Message;
    }

    protected String getSender () throws Exception
    {
        return _Message.getFrom ()[0].toString ();
    }

    public String getSubject () throws Exception
    {
        return _Message.getSubject ();
    }

    protected void performOperations () throws Exception
    {
        visitParts (_Message);
    }

    public void setMessage (MimeMessage _Message)
    {
        this._Message = _Message;
    }

    protected void setupEnvironment (HttpServletRequest req, HttpServletResponse resp) throws Exception
    {
        Properties props = new Properties ();
        Session email = Session.getDefaultInstance (props, null);
        _Message = new MimeMessage (email, req.getInputStream ());
    }

    protected void teardownEnvironment ()
    {
    }

    protected void visitParts (Part aPart) throws Exception
    {
        new BeanMimeParser (this).parse (aPart);
    }
}
